import {Command} from '@ckeditor/ckeditor5-core';
import {findOptimalInsertionRange} from '@ckeditor/ckeditor5-widget';

export default class UploadVideoCommand extends Command {

    refresh() {
        const model = this.editor.model;
        const selection = model.document.selection;
        const selectedVideo = getSelectedVideoModelWidget(selection);
        this.value = selectedVideo ? selectedVideo.getAttribute('url') : null;
        this.isEnabled = isVideoSelected(selection) || isAllowedInParent(selection, model);
    }

    execute(url) {
        const model = this.editor.model;
        const selection = model.document.selection;
        const selectedVideo = getSelectedVideoModelWidget(selection);
        if (selectedVideo) {
            model.change(writer => {
                writer.setAttribute('url', url, selectedVideo);
            });
        } else {
            this.insertVideo(url);
        }
    }

    insertVideo(url) {
        const model = this.editor.model;
        model.change(writer => {
            model.insertContent(writer.createElement('videoBlock', {
                src: url, controls: 'controls', style: 'display:block;width:100%;height:100%', preload: 'auto',
            }), model.document.selection);
        });
    }
}

function isAllowedInParent(selection, model) {
    const insertionRange = findOptimalInsertionRange(selection, model);
    let parent = insertionRange.start.parent;
    if (parent.isEmpty && !model.schema.isLimit(parent)) {
        parent = parent.parent;
    }
    return model.schema.checkChild(parent, 'videoBlock');
}

function isVideoSelected(selection) {
    const element = selection.getSelectedElement();
    return !!element && element.name === 'video';
}

function getSelectedVideoModelWidget(selection) {
    const selectedElement = selection.getSelectedElement();
    if (selectedElement && selectedElement.is('element', 'video')) {
        return selectedElement;
    }
    return null;
}